<template>
    <view class="page">
        <SelectLocation :locationName.sync="form.s_name"
                        :locationLng.sync="form.s_lng"
                        :locationLat.sync="form.s_lat"
                        :locationAddress.sync="form.s_address"
                        :show="showLocation" @cancel="showLocation=false;"></SelectLocation>
        <view class="content">
            <u-form labelPosition="left"
                    labelWidth="90"
                    :model="form"
                    ref="uForm">
                <u-form-item prop="s_name">
                    <view style="display: flex;flex-direction: row;justify-content: space-between">
                        <u-input v-model="form.s_name" :disabled="true" border="none"/>
                        <text style="color: #2979ff" v-if="form.s_name" @click="reSelect">重新选择 > </text>
                    </view>
                </u-form-item>
                <u-form-item label="栋/大楼" prop="building" borderBottom>
                    <u-input v-model="form.building" border="none" placeholder="第几栋/大楼"/>
                </u-form-item>
                <u-form-item label="单元" prop="unit" borderBottom>
                    <u-input v-model="form.unit" border="none" placeholder="第几单元"/>
                </u-form-item>
                <u-form-item label="户室号" prop="room_num" borderBottom>
                    <u-input v-model="form.room_num" border="none" placeholder="户室号"/>
                </u-form-item>
                <u-form-item label="开锁方式" prop="lock_type" borderBottom>
                    <u-radio-group
                            v-model="form.lock_type"
                            placement="row">
                        <u-radio label="钥匙" name="1"></u-radio>
                        <u-radio label="智能" name="2"></u-radio>
                    </u-radio-group>
                </u-form-item>
                <u-form-item label="电梯" prop="is_elveator" borderBottom>
                    <u-radio-group
                            v-model="form.is_elveator"
                            placement="row">
                        <u-radio label="有" name="1"></u-radio>
                        <u-radio label="无" name="0"></u-radio>
                    </u-radio-group>
                </u-form-item>

                <u-form-item label="公区特色" prop="public_special_id" borderBottom>
                    <u-checkbox-group
                            v-model="form.public_special_id"
                            placement="row">
                        <u-checkbox v-for="(item,index) in publicData" :label="item.name" :name="item.id" :key="index"></u-checkbox>
                    </u-checkbox-group>
                </u-form-item>
                <u-form-item label="房屋朝向" prop="orientation" borderBottom @click="clickFace">
                    <u--input
                            v-model="form.orientation"
                            disabled
                            disabledColor="#ffffff"
                            placeholder="请选择房屋朝向"
                            border="none"
                    ></u--input>
                    <u-icon
                            slot="right"
                            name="arrow-right"
                    ></u-icon>
                </u-form-item>
                <u-form-item label="出租状态" prop="rent_type" borderBottom>
                    <u-radio-group
                            v-model="form.rent_type"
                            placement="row">
                        <u-radio label="已租" name="2"></u-radio>
                        <u-radio label="未租" name="1"></u-radio>
                    </u-radio-group>
                </u-form-item>
                <u-form-item label="租金(元/月)" prop="lease_priec" borderBottom>
                    <u-input v-model="form.lease_priec" border="none" placeholder="租金"/>
                </u-form-item>
                <u-form-item label="面积（㎡）" prop="area" borderBottom>
                    <u-input v-model="form.area" border="none" placeholder="请输入面积"/>
                </u-form-item>
                <u-form-item label="房源户型" prop="house_type" borderBottom @click="clickHouseType">
                    <u--input
                            v-model="house_type"
                            disabled
                            disabledColor="#ffffff"
                            placeholder="请选择房源户型"
                            border="none"
                    ></u--input>
                    <u-icon
                            slot="right"
                            name="arrow-right"
                    ></u-icon>
                </u-form-item>
                <text>上传房间图片(最多上传4张)</text>
                <u-upload
                        :fileList="houseImgList"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        name="house"
                        multiple
                        :maxCount="4"
                ></u-upload>
                <text>公共区域图片(最多上传4张)</text>
                <u-upload
                        :fileList="areaImgList"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        name="area"
                        multiple
                        :maxCount="4"
                ></u-upload>
            </u-form>
            <u-action-sheet
                    :show="showFace"
                    :actions="faceList"
                    title="请选择房屋朝向"
                    @close="showFace = false"
                    @select="faceSelect"
            >
            </u-action-sheet>
            <u-picker :show="showHouseType" :columns="houseTypeColumns" @confirm="houseTypeConfirm" @cancel="cancelHouseType"></u-picker>
            <u-row>
                <u-button type="default" :plain="true" text="完成录入" @click="submit"></u-button>
                <u-button type="primary" text="继续录入" @click="submit(true)"></u-button>
            </u-row>
        </view>
        <view class="safe-area-inset-bottom"></view>
    </view>
</template>

<script>
    import SelectLocation from './components/SelectLocation';

    export default {
        name: "whole",
        components: {
            SelectLocation
        },
        onLoad(){
            this.getPublicAreaData();
        },
        // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
        onReady() {
            this.$refs.uForm.setRules(this.rules);
        },
        data() {
            return {
                showLocation: true,
                type: 3, //1精品公寓 2分散式合租 3分散式整租
                showFace: false,
                showHouseType: false,
                publicData:[],
                houseTypeColumns:[
                    ['无','一室', '二室','三室','四室','五室','六室','七室','八室'],
                    ['无','一厅', '二厅','三厅','四厅','五厅','六厅'],
                    ['无','一卫', '二卫', '三卫','四卫','五卫','六卫']
                ],
                faceList: [{
                    name: '东'
                }, {
                    name: '南'
                }, {
                    name: '西'
                }, {
                    name: '北'
                }],
                houseTypeList:[{
                    name: '一室一厅',
                },{
                    name: '两室一厅',
                }],
                houseImgList:[],
                areaImgList:[],
                house_type:'',
                form: {
                    s_name:'',
                    s_lng:'',
                    s_lat:'',
                    s_address:'',
                    building: '',
                    unit:'',
                    room_num:'',
                    lock_type:'',
                    is_elveator:'',
                    public_special_id:[],
                    office:'', // 室
                    section:'', // 厅
                    hygiene:'', // 卫
                    orientation:'',
                    rent_type:'',
                    lease_priec:'',
                    area:'',
                },
                rules: {
                    s_name: [{type: 'string', required: true, message: '请输入小区名称', trigger: ['blur', 'change']}],
                    building: [{required: true, message: '请输入几号楼', trigger: ['blur', 'change']}],
                    unit: [{required: true, message: '请输入单元', trigger: ['blur', 'change']}],
                    room_num: [{required: true, message: '请输入房号', trigger: ['blur', 'change']}],
                    lock_type: [{required: true, message: '请输入开锁方式', trigger: ['blur', 'change']}],
                    is_elveator: [{required: true, message: '请输入电梯', trigger: ['blur', 'change']}],
                    public_special_id: [{type: 'array', required: true, message: '请输入公区特色', trigger: ['change']}],
                    office: [{required: true, message: '请输入几室', trigger: ['blur', 'change']}],
                    section: [{required: true, message: '请输入几厅', trigger: ['blur', 'change']}],
                    hygiene: [{required: true, message: '请输入几卫', trigger: ['blur', 'change']}],
                    orientation: [{type: 'string',max: 1, required: true, message: '请输入朝向', trigger: ['blur', 'change']}],
                    rent_type: [{required: true, message: '请输入出租状态', trigger: ['blur', 'change']}],
                    lease_priec: [{required: true, message: '请输入租金', trigger: ['blur', 'change']}],
                    area: [{required: true, message: '请输入面积', trigger: ['blur', 'change']}],
                }
            }
        },
        methods: {
            getPublicAreaData() {
                uni.$u.http.get('/api.php/house/house_special').then(res => {
                    for (let i = 0; i < res.length; i++) {
                        if (res[i].type === 1){
                            this.publicData.push(res[i]);
                        }
                    }
                });
            },
            clickFace(){
                this.showFace = true;
                uni.hideKeyboard();
            },
            clickHouseType(){
                this.showHouseType = true;
                uni.hideKeyboard();
            },
            cancelHouseType(){
                this.showHouseType = false;
            },
            faceSelect(e) {
                this.form.orientation = e.name;
                this.$refs.uForm.validateField('orientation')
            },
            houseTypeConfirm(e) {
                console.log('confirm', e);
                this.form.office = e.indexs[0];
                this.form.section = e.indexs[1];
                this.form.hygiene = e.indexs[2];
                this.house_type = e.value.join('/');

                this.showHouseType = false;
            },

            // 删除图片
            deletePic(event) {
                this[`${event.name}ImgList`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`${event.name}ImgList`].length
                lists.map((item) => {
                    this[`${event.name}ImgList`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    let item = this[`${event.name}ImgList`][fileListLen]
                    this[`${event.name}ImgList`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
            },
            uploadFilePromise(url) {
                let server = this.$url + '/api.php/index/file_update';
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: server,
                        filePath: url,
                        name: 'image[]',
                        success: (res) => {
                            let resp = JSON.parse(res.data);
                            setTimeout(() => {
                                resolve(resp.data.img_url[0]);
                            }, 1000)
                        }
                    });
                })
            },
            submit(is_continue = false) {
                this.$refs.uForm.validate().then(res => {
                    uni.showLoading({title: '正在加载'});

                    let data = uni.$u.deepClone(this.form);

                    data.type = this.type;
                    data.u_id = uni.getStorageSync('u_id');
                    data.public_special_id = data.public_special_id.join();
                    let array = [];
                    for (let i = 0; i < this.houseImgList.length; i++) {
                        array.push(this.houseImgList[i].url);
                    }
                    data.room_img = array.join();

                    array = [];
                    for (let i = 0; i < this.areaImgList.length; i++) {
                        array.push(this.areaImgList[i].url);
                    }
                    data.join_public_img = array.join();

                    uni.$u.http.post('/api.php/house/house_add', data).then(res => {
                        uni.hideLoading();
                        uni.showToast({
                            title: '添加成功', //提示文字
                            duration: 3000, //显示时长
                            icon: "none", //图标，支持"success"、"loading"
                        });
                    });

                    if (is_continue) {
                        uni.redirectTo({url: '/pages/landlord/plus/whole'});
                    }else{
                        uni.navigateBack({delta: 1});
                    }
                }).catch(errors => {
                    uni.$u.toast('校验失败');
                    return false;
                });
            },
            // 重新选择小区
            reSelect(){
                this.showLocation = true;
            },
        }
    }
</script>

<style scoped>
    .page {
        width: 100%;
        min-height: 100vh;
        /*background-color: RGBA(245, 245, 245, 1);*/
        /*background-color: #f3f4f6;*/
        background-color: #ffffff;
    }

    .content {
        padding: 20rpx;
    }

    /deep/ .u-text {
        padding: 20rpx;
        background-color: #f3f4f6;
    }

    /deep/ .u-radio {
        margin-right: 16px;
    }

    /deep/ .u-checkbox {
        margin-right: 16px;
    }
</style>